layui.define(['table','grid', 'jquery', 'form'], function (exports) {
    "use strict";

    var MOD_NAME = 'selectTable',
        $ = layui.jquery,
        table = layui.table,
        form = layui.form;
        
    var tableSelect = function () { this.v = '1.1.0'; };

    /**
    * 初始化表格选择器
    */
    tableSelect.prototype.render = function (opt) {
        var elem = $(opt.elem);
        var tableDone = opt.done || function(){};
		
        //默认设置
        opt.gridId = opt.gridId || '';
        
        elem.attr('readonly','readonly');
        elem.off('click').on('click', function(e) {
            e.stopPropagation();
            if($('div.tableSelect').length >= 1) return false;
            
            var t = elem.offset().top + elem.outerHeight()+"px";
            var l = elem.offset().left +"px";
            
            var html = `
            	<div class="tableSelect layui-anim layui-anim-upbit" style="left:${l};top:${t};border: 1px solid #d2d2d2;background: #fff;box-shadow: 0 2px 4px rgba(0,0,0,.12);padding:3px;position: absolute;z-index:6666;margin: 5px 0;border-radius: 2px;width:530px;height:320px;">
	           		<div style="text-align:right;padding:3px 5px;position:absolute;right: 5px;top: 8px;z-index:11;">
	            		<button type="button" class="layui-btn layui-btn-normal layui-btn-sm confirm">
	            			确 认
	            		</button>
	            	</div> 	
	            	<div id="${opt.gridId}"></div>
            	</div>
            `;
          	var tableBox  = $($.trim(html));   $('body').append(tableBox);
            
			//FIX位置
			var overHeight = (elem.offset().top + elem.outerHeight() + tableBox.outerHeight() - $(window).scrollTop()) > $(window).height();
			var overWidth = (elem.offset().left + tableBox.outerWidth()) > $(window).width();
			    overHeight && tableBox.css({'top':'auto','bottom':'0px'});
			    overWidth && tableBox.css({'left':'auto','right':'5px'})
			
			//初始化列表
            var  grid= layui.grid.render(opt.gridId); 
            grid.load([]);    
            grid.loadSuccess(function(){
            	$(`#${opt.gridId}`).find('.xw-search input').eq(0).focus();
            });
			
			//确认
			tableBox.on('click','.confirm',function(){
				var rows = grid.getSelectedRows();
				if(!rows[0]) return $.toast(0,'请选择！');
				tableDone( elem , rows );
				tableBox.remove();
			});
			
            //点击其他区域关闭
            $(document).click(function(e){
                var userSet_con = $('.tableSelect');
                if(!userSet_con.is(e.target) && userSet_con.has(e.target).length === 0){
                    tableBox.remove();
                }
            });
        });
    }


    //自动完成渲染
    var tableSelect = new tableSelect();

    //FIX 滚动时错位
    if(window.top == window.self){
        $(window).scroll(function () {
            tableSelect.hide();
        });
    }
	
    exports(MOD_NAME, tableSelect);
})